import router from './router'
import store from './store'

// 进度条
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

import { asyncRoutes } from './router'
// 进度条配置
NProgress.configure({ showSpinner: false }) // NProgress Configuration
// 白名单
const whiteList = ['/login', '/404'] // no redirect whitelist

// 前置守卫
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // determine whether the user has logged in
  const token = store.getters.token

  if (token) {
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/storeGetUserInfo')
        const actionRoutes = asyncRoutes.filter(item => {
          return roles.menus.includes(item.name)
        })
        // console.log(roles)
        router.addRoutes([...actionRoutes, { path: '*', redirect: '/404', hidden: true }])
        // console.log(actionRoutes)
        store.commit('user/updateRoutes', actionRoutes)
        next(to.path) // 目的是让路由拥有信息 router的已知缺陷
      }

      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      NProgress.done()
    }
  }
})

// 后置守卫
router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
